import Vue from 'vue';
import { TokenKey, getToken, setToken, removeToken } from '@/utils/auth';

const state = {
    // 用户名称
    userName: '',
    // 用户Id
    userId: '',
    // 用户手机号
    userPhone: ''
};

const getters = {

};

const mutations = {
    SET_USER_ID: (state, userId) => {
        state.userId = userId
    },
    SET_USER_NAME: (state, userName) => {
        state.userName = userName
    },
    SET_USER_PHONE: (state, userPhone) => {
        state.userPhone = userPhone
    }
};

const actions = {
    /**
     * 手机号验证码登录
     * @param commit
     * @param loginForm   登录表单参数
     */
    loginByCode({ commit }, loginForm) {
        return new Promise((resolve, reject) => {
            Vue.prototype.$request(Vue.prototype.$api.store.login_loginH5ByCode, loginForm).then(data => {
                // 存储信息
                setToken(data.token);
                commit('SET_USER_ID', data.userId);
                commit('SET_USER_PHONE', data.phone);
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    /**
     * 手机号密码登录
     * @param commit
     * @param loginForm   登录表单参数
     */
    loginByPsd({ commit }, loginForm) {
        return new Promise((resolve, reject) => {
            Vue.prototype.$request(Vue.prototype.$api.store.login_loginH5ByPwd, loginForm).then(data => {
                // 存储信息
                setToken(data.token);
                commit('SET_USER_ID', data.userId);
                commit('SET_USER_NAME', data.userName);
                commit('SET_USER_PHONE', data.phone);
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    /**
     * 修改名称
     * @param commit
     * @param userName  用户名称
     */
    updateUserName({ commit }, userName) {
        commit('SET_USER_NAME', userName)
    },
    /**
     * 通过token获取用户信息
     * @param commit
     */
    getUserInfoByToken({ commit }) {
        return new Promise((resolve, reject) => {
            Vue.prototype.$request(Vue.prototype.$api.store.user_queryByToken, {}).then(data => {
                // 存储信息
                commit('SET_USER_ID', data.id);
                commit('SET_USER_NAME', data.name);
                commit('SET_USER_PHONE', data.phone);
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    /**
     *  退出登录
     * @param commit
     */
    logOut({ commit }) {
        return new Promise((resolve, reject) => {
            // 清除数据
            commit('SET_USER_ID', '');
            commit('SET_USER_NAME', '');
            commit('SET_USER_PHONE', '');
            removeToken();
            localStorage.removeItem('STORE_INFO');
        })
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}
